package commonality.updater;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.widget.Toast;

import static commonality.updater.ConTextAPI.APP_ID;


/**
 * 更新管理器
 * <p>
 * Created by maimingliang
 */
@SuppressWarnings("unused")
public class UpdateAppManager {

    @SuppressWarnings("unused")
    private static final String TAG = "UpdateAppManager";

    /**
     * 下载APK文件
     *
     * @param context
     * @param url
     * @param title
     * @param appName
     */
    public static void downloadApkS(Context context, String url, String title, final String appName) {

        //获取存储的下载ID
        long downloadId = (long) SpUtils.getInstance(context).getLong(APP_ID, -1L);
        if (downloadId != -1) {
            //存在downloadId
            DownLoadUtils downLoadUtils = DownLoadUtils.getInstance(context);
            //获取当前状态
            int status = downLoadUtils.getDownloadStatus(downloadId);
            if (DownloadManager.STATUS_SUCCESSFUL == status) {
                //状态为下载成功
                //获取下载路径URI
                Uri downloadUri = downLoadUtils.getDownloadUri(downloadId);
                if (null != downloadUri) {
                    //存在下载的APK，如果两个APK相同，启动更新界面。否之则删除，重新下载。
                    if (compare(getApkInfo(context, downloadUri.getPath()), context)) {
                        startInstall(context, downloadUri);
                        return;
                    } else {
                        //删除下载任务以及文件
                        downLoadUtils.getDownloadManager().remove(downloadId);
                    }
                }
                start(context, url, title, appName);
            } else if (DownloadManager.STATUS_FAILED == status) {
                //下载失败,重新下载
                start(context, url, title, appName);
            } else if (-1 == status) {
                //下载失败,重新下载
                start(context, url, title, appName);
            } else {
                Toast.makeText(context, "文件正在下载中，请打开设置-下载管理中查看", Toast.LENGTH_SHORT).show();
            }
        } else {
            //不存在downloadId，没有下载过APK
            start(context, url, title, appName);
        }
    }

    /**
     * 开始下载
     *
     * @param context
     * @param url
     * @param title
     * @param appName
     */
    private static void start(Context context, String url, String title, String appName) {
        if (hasSDKCard()) {
            long id = DownLoadUtils.getInstance(context).download(url,
                    title, "版本更新", appName);
            SpUtils.getInstance(context).putLong(APP_ID, id);
        } else {
            Toast.makeText(context, "下载失败", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 是否存在SD卡
     */
    private static boolean hasSDKCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 比较两个APK的信息
     *
     * @param apkInfo
     * @param context
     * @return
     */
    private static boolean compare(PackageInfo apkInfo, Context context) {

        if (null == apkInfo) {
            return false;
        }
        String localPackageName = context.getPackageName();
        if (localPackageName.equals(apkInfo.packageName)) {
            try {
                PackageInfo packageInfo = context.getPackageManager().getPackageInfo(localPackageName, 0);
                //比较当前APK和下载的APK版本号
                if (apkInfo.versionCode > packageInfo.versionCode) {
                    //如果下载的APK版本号大于当前安装的APK版本号，返回true
                    return true;
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 获取APK程序信息
     *
     * @param context
     * @param path
     * @return
     */
    private static PackageInfo getApkInfo(Context context, String path) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        if (null != pi) {
            return pi;
        }
        return null;
    }


    /**
     * 跳转到安装界面
     *
     * @param context
     * @param uri
     */
    private static void startInstall(Context context, Uri uri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(uri, "application/vnd.android.package-archive");
            context.startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(uri, "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install);
        }


        /*
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(install);*/
    }


}
